package com.ideal.service;

import com.ideal.tools.db.MysqlDBUtils;
import com.ideal.tools.ssh.entity.LinuxMachine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by CC on 2016/7/26.
 * 这个类之在service里面用
 * 我实在是想用这样的方式提供 一些操作封装
 * 但是没办法我 暂时想不到其他方法
 */
public class Utils {

    private static final Logger logger = LoggerFactory.getLogger(Utils.class);

    public static Map<String,LinuxMachine> getTotalMachineInfo(){
        String sql="select cluster_machine.id as id,cluster_machine.machineip as ip,cluster_machine.loginusername username," +
                "cluster_machine.loginpassword pwd,cluster_machine_type.machineTypeName typeid from cluster_machine " +
                "left join cluster_machine_type on cluster_machine.machineTypeId=cluster_machine_type.machineTypeId";
        Map<String,LinuxMachine> machineMap=new HashMap<String, LinuxMachine>();
        List<Map<String,Object>> rows = MysqlDBUtils.queryWebDB(sql);
        for(Map<String,Object> row:rows){
            String id=row.get("id").toString();
            String ip=row.get("ip").toString();
            String username=row.get("username").toString();
            String pwd=row.get("pwd").toString();
            String typeid=row.get("typeid").toString();

            LinuxMachine linuxMachine=new LinuxMachine();
            linuxMachine.initIP(ip).initLoginName(username).initPassWord(pwd)
                    .initMachineType(LinuxMachine.MachineType.getEnumMachineType(typeid));

            machineMap.put(id,linuxMachine);
        }
        return machineMap;
    }

    public static List<LinuxMachine> getTotalMachineInfoList(){
        List<LinuxMachine> machineList = new ArrayList<LinuxMachine>();
        Map<String,LinuxMachine> machineMap = getTotalMachineInfo();
        for(Map.Entry<String,LinuxMachine> entry:machineMap.entrySet()){
            machineList.add(entry.getValue());
        }
        return machineList;
    }

    /**
     * 获取用户的 id -> name 的对照字典
     * @return
     */
    public static Map<String,String> getUserMapReserve(){
        String sql="select id pkey,username pval from cluster_user";
        List<Map<String,Object>> rows = MysqlDBUtils.queryWebDB(sql);
        Map<String,String> map=new HashMap<String, String>();

        for(Map<String,Object> row:rows){
            String key=row.get("pkey").toString();
            String val=row.get("pval").toString();
            map.put(val,key);
        }
        return map;
    }

    /**
     * 获取机器的 id -> ip 的字典
     * @return
     */
    public static Map<String,String> getMachineMap(){
        String sql="select id pkey,machineip pval from cluster_machine";
        List<Map<String,Object>> rows = MysqlDBUtils.queryWebDB(sql);
        Map<String,String> map=new HashMap<String, String>();

        for(Map<String,Object> row:rows){
            String key=row.get("pkey").toString();
            String val=row.get("pval").toString();
            map.put(key,val);
        }
        return map;
    }

    /**
     * 获取机器的 ip->id
     * @return
     */
    public static Map<String,String> getCltReservMap(){
        String sql="select id pkey,machineip pval from cluster_machine where machinetypeid=3";
        List<Map<String,Object>> rows = MysqlDBUtils.queryWebDB(sql);
        Map<String,String> map=new HashMap<String, String>();

        for(Map<String,Object> row:rows){
            String key=row.get("pkey").toString();
            String val=row.get("pval").toString();
            map.put(val,key);
        }
        return map;
    }

    /**
     * 写入 linux 文件
     * @param path
     * @param sb
     */
    public static void writeLinuxFile(String path,StringBuffer sb){
        File file=new File(path);
        BufferedWriter writer=null;
        try {
            if(!file.exists()){
                file.createNewFile();
            }
            writer=new BufferedWriter(new FileWriter(file));
            writer.write(sb.toString());
            writer.flush();

//            for(String c:content){
//                writer.write(c);
//                writer.flush();
//            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (writer!=null){
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取 txt 文件
     * @param path
     * @return
     */
    public static List<String> readFile2List(String path){
        List<String> txtList=new ArrayList<String>();

        File file=new File(path);

        if(!file.exists()){
            logger.info("Path["+path+"] is not exited!");
            return null;
        }

        BufferedReader reader=null;

        try {
            reader=new BufferedReader(new FileReader(file));

            String tmp="";

            while((tmp=reader.readLine())!=null){
//                logger.info(tmp);
                txtList.add(tmp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(reader!=null)
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return txtList;
    }


    /**
     * 执行一条本地命令
     * @param cmd
     * @return
     */
    public static String exeLocalCMD(String cmd) {
        StringBuffer cmdout = new StringBuffer();
        logger.info("execute local command ：" + cmd);
        BufferedReader br=null;
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            InputStream fis = process.getInputStream();
            br = new BufferedReader(new InputStreamReader(fis));
            String line = null;

            while ((line = br.readLine()) != null) {
                cmdout.append(line).append(System.getProperty("line.separator"));
            }

            logger.info("executer local result：" + cmdout.toString() + "/n");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (br!=null)
                    br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return cmdout.toString().trim();
    }


    public static int exeLocalSudoCMD(String cmd) {
        int rs=0;
        StringBuffer cmdout = new StringBuffer();
        logger.info("execute local command ：" + cmd);
        BufferedReader br=null;
        String[] cmds ={"/bin/bash", "-c", "sudo "+cmd };
        try {
            Process process = Runtime.getRuntime().exec(cmds);
            InputStream fis = process.getInputStream();
            br = new BufferedReader(new InputStreamReader(fis));
            String line = null;

            while ((line = br.readLine()) != null) {
                cmdout.append(line).append(System.getProperty("line.separator"));
            }

            logger.info("executer local result：" + cmdout.toString()+"/n");
//            return process.exitValue();
        } catch (IOException e) {
            e.printStackTrace();
            rs=-1;
        }finally {
            try {
                if (br!=null)
                    br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return rs;
    }

    //解析时间
    public static String parseStringToDate(String start,String fomat) {
        String time = "";
        //"MM/dd/yy HH:mm:ss"
        SimpleDateFormat format=new SimpleDateFormat(fomat);
        try {
            Date date = format.parse(start);
            time = String.valueOf(date.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }


    /**
     * 读取 SQL 文件，获取 SQL 语句
     * @param sqlFile SQL 脚本文件
     * @return List<sql> 返回所有 SQL 语句的 List
     * @throws Exception
     */
    public static List<String> loadSql(String sqlFile) throws Exception {
        List<String> sqlList = new ArrayList<String>();

        try {
            InputStream sqlFileIn = null;
            if (sqlFile.startsWith("classpath:")) {
                sqlFile = sqlFile.replace("classpath:","");
                sqlFileIn = Utils.class.getResourceAsStream(sqlFile);
            }else
                sqlFileIn = new FileInputStream(sqlFile);

            StringBuffer sqlSb = new StringBuffer();
            byte[] buff = new byte[1024];
            int byteRead = 0;
            while ((byteRead = sqlFileIn.read(buff)) != -1) {
                sqlSb.append(new String(buff, 0, byteRead));
            }

            // Windows 下换行是 /r/n, Linux 下是 /n
            String[] sqlArr = sqlSb.toString().split("(;\\s*\\r\\n)|(;\\s*\\n)");
            for (int i = 0; i < sqlArr.length; i++) {
                String sql = sqlArr[i].replaceAll("--.*", "").trim();
                if (!sql.equals("")) {
                    sqlList.add(sql);
                }
            }
            return sqlList;
        } catch (Exception ex) {
            throw new Exception(ex.getMessage());
        }
    }
}
